/***
 * CaRComp Translator
 * 
 * Copyright (C) 2011 Taylor L. Riche
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 ***/

package translator.objects;

import java.util.*;
import java.io.*;

public class Algorithm extends Entity {

	protected Map<String, Port> p_map;
	protected Map<String, Port> p_registry;
	protected Map<String, Component> c_map;
	protected Map<String, Connector> cn_map;
	
	public Algorithm(String ident, String name, Map<String, Port> p_map, Map<String, Component> c_map, Map<String, Connector> cn_map) {
		super(ident, name);
		this.p_map = p_map;
		this.c_map = c_map;
		this.cn_map = cn_map;
		this.p_registry = new HashMap<String, Port>();
		p_registry.putAll(p_map);
		for(Port p : this.p_map.values()) {
			p.setCompID(this.getIdent());
		}
	}

	@Override
	public void generateCode(PrintStream fo) {
		fo.println("from ft.framework import abstraction");
		for (Component c: this.c_map.values()) {
			c.generateInclude(fo);
			this.p_registry.putAll(c.p_map);
		}
		fo.println();
		fo.println("class " + this.getName() + "(abstraction.Abstraction):");
		fo.println();
		fo.println("\tdef __init__(self, name):");
		fo.println("\t\tabstraction.Abstraction.__init__(self, name)");
		for (Component c : this.c_map.values()) {
			c.generateCode(fo);
		}
		for (Port p : this.p_map.values()) {
			p.generateCode(fo);
		}
		for (Connector cn : this.cn_map.values()) {
			String sc_name;
			if (this.p_registry.get(cn.getSourceID()).getCompID().equals(this.getIdent())) {
				sc_name = this.getNID();
			}
			else {
				sc_name = this.c_map.get(this.p_registry.get(cn.getSourceID()).getCompID()).getNID();
			}
			String sp_name = this.p_registry.get(cn.getSourceID()).getName();
			String dc_name;
			if (this.p_registry.get(cn.getDestinationID()).getCompID().equals(this.getIdent())) {
				dc_name = this.getNID();
			}
			else {
				dc_name = this.c_map.get(this.p_registry.get(cn.getDestinationID()).getCompID()).getNID();
			}
			String dp_name = this.p_registry.get(cn.getDestinationID()).getName();
			cn.setNames(sc_name, sp_name, dc_name, dp_name);
			cn.generateCode(fo);
		}
	}

}
